import { actionTypeCreatorWithNameSpace, createAction } from './util';
import agent from 'agent';

const actionTypeCreator = actionTypeCreatorWithNameSpace('company');

export const listByCurrentUser = createAction(actionTypeCreator('listByCurrentUser'), () => {
  return agent.get('/api/users/current/companies')
    .then(response => response.body);
}, {
  fetch: {
    processing: true
  }
});

export const search = createAction(actionTypeCreator('search'), query => {
  return agent.get('/api/companies/search')
    .query(query)
    .then(response => response.body);
}, {
  fetch: {
    processing: true
  }
});

export const create = createAction(actionTypeCreator('create'), company => {
  return agent.post('/api/companies')
    .send(company)
    .then(response => response.body);
});

export const update = createAction(actionTypeCreator('update'), company => {
  return agent.put(`/api/companies/${company.id}`)
    .send(company)
    .then(response => response.body);
});

export const authTeam = createAction(actionTypeCreator('authTeam'), (companyId, teamId) => {
  return agent.post(`/api/companies/${companyId}/dev-teams`)
    .type('form')
    .send({ teamId })
    .then(() => teamId);
}, {
  fetch: {
    processing: true
  }
});

export const unAuthTeam = createAction(actionTypeCreator('unAuthTeam'), (companyId, teamId) => {
  return agent.del(`/api/companies/${companyId}/dev-teams/${teamId}`)
    .then(() => teamId);
}, {
  fetch: {
    processing: true
  }
});

export const listAuthedDevTeams = createAction(actionTypeCreator('listAuthedDevTeams'), (companyId) => {
  return agent.get(`/api/companies/${companyId}/dev-teams`)
    .then(response => response.body);
}, {
  fetch: {
    processing: true
  }
});

export const managedCompany = createAction(actionTypeCreator('managedCompany'), (devTeamId) => {
  const query = {devTeamId}
  return agent.get('/api/users/current/company/managed')
    .query(query)
    .then(response => response.body);
}, {
  fetch: {
    processing: true
  }
});

export const listRunnableGroups = createAction(actionTypeCreator('listRunnableGroups'), (companyId) => {
  return agent.get(`/api/companies/${companyId}/runnable-groups`)
    .then(response => response.body);
}, {
  fetch: {
    processing: true
  }
});

export const listMachines = createAction(actionTypeCreator('listMachines'), (companyId) => {
  return agent.get(`/api/companies/${companyId}/machines`)
    .then(response => response.body);
}, {
  fetch: {
    processing: true
  }
});
